#include "type.h"
#include "LPC11xx.h"
#include "key.h"

extern volatile uint32_t I2CMasterState;
extern volatile uint32_t I2CSlaveState;
extern volatile uint32_t timeout;
extern volatile uint32_t I2CMode;

extern volatile uint8_t I2CMasterBuffer[BUFSIZE];
extern volatile uint8_t I2CSlaveBuffer[BUFSIZE];
extern volatile uint32_t I2CCount;
extern volatile uint32_t I2CReadLength;
extern volatile uint32_t I2CWriteLength;

static void delay(void)
{
   uint32_t i;
   for(i=0;i<0x9000;i++);
}

uint8_t getkey(void)
{
   uint8_t k1=0xff,k2=0xff,kval=0xff;
   //static uint8_t kvold=0xff;

   if(I2CInit(I2CMASTER)==FALSE) while(1);
   I2CWriteLength=2;
   I2CReadLength=1;
   I2CMasterBuffer[0]=PCF8574_KEY;
   I2CMasterBuffer[1]=0x0f;
   I2CMasterBuffer[2]=PCF8574_KEY | RD_BIT;
   I2CEngine();
   delay();
   switch (I2CSlaveBuffer[0])
   {
      case 0x0e:
	     k1=1;
	     break;
	  case 0x0d:
	     k1=2;
		 break;
	  case 0x0b:
	     k1=3;
		 break;
	  case 0x07:
	     k1=4;
		 break;
	  default:
	     k1=0;
		 kval=0;
		 break;
   }

   I2CWriteLength=2;
   I2CReadLength=1;
   I2CMasterBuffer[0]=PCF8574_KEY;
   I2CMasterBuffer[1]=0xf0;
   I2CMasterBuffer[2]=PCF8574_KEY | RD_BIT;
   I2CEngine();
   delay();
   switch (I2CSlaveBuffer[0])
   {
      case 0xe0:
	     k2=1;
	     break;
	  case 0xd0:
	     k2=2;
		 break;
	  case 0xb0:
	     k2=3;
		 break;
	  case 0x70:
	     k2=4;
		 break;
	  default:
	     k2=0;
		 kval=0;
		 break;
   }
   if(kval==0xff) kval=(k1-1)*4+k2;
   //if(kval==kvold) kval=0xff;
   //else kvold=kval;
   return kval;
}
